package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    /*
        认证的方法
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        String email = usernamePasswordToken.getUsername();

        User user = userService.findByEmail(email);

        //如果找不到用户，返回null，用户不存在
        if (user==null){
            return null;
        }

        /*创建AuthenticationInfo对象，然后把该用户的数据库密码传入，然后shiro自己从token中获取密码进行对比*/
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), "");

        return simpleAuthenticationInfo;
    }

    /*
        授权的方法
        用户登录成功之后就会调用该方法给用户去授权
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //登录成功的用户
        User user = (User) principals.getPrimaryPrincipal();
        System.out.println("授权了。。。。");
        //查找该用户所拥有的权限
        List<Module> moduleList = moduleService.findModuleByUser(user);

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        for (Module module : moduleList) {
            simpleAuthorizationInfo.addStringPermission(module.getName());
        }
        return simpleAuthorizationInfo;
    }


}
